<template>
	<view class="page page-publish">
		<view p10px>
			<uni-title type="h3" title="产品信息"></uni-title>
			<view class="border-b" my-5px pb-5px>
				<view>{{type? '供应' : '求购'}}类型</view>
				<uni-data-picker 
					:localdata="types" 
					v-model="typesPicked" 
					:map="{text:'name',value:'id'}" 
					:clear-icon="false" 
					:placeholder="`请选择${type? '供应' : '求购'}类型`"
					:popup-title="`${type? '供应' : '求购'}类型`"
				/>
			</view>
			<view flex items-center justify-between mt5px mb5px>
				<view>产品名称</view>
				<uni-easyinput color-gray v-model="name" :inputBorder="false" placeholder="请输入产品名称  &nbsp;"></uni-easyinput>
			</view>
		</view>
		<view h10px bg-gray-2></view>
		<view p10px>
			<uni-title type="h3" :title="`${type? '供应' : '求购'}信息`"></uni-title>
			<view flex items-center justify-between pt5px pb5px border-b>
				<view>价格面议</view>
				<switch :checked="priceSwitch" style="transform:scale(0.7)" @change="switchChange" />
			</view>
			<view flex items-center justify-between pt5px pb5px border-b v-if="!priceSwitch">
				<view>产品价格</view>
				<uni-easyinput color-gray v-model="price" type="digit" :inputBorder="false" placeholder="请输入产品价格  &nbsp;"></uni-easyinput>
			</view>
			<view flex items-center justify-between pt5px pb5px border-b>
				<view>{{type? '供应' : '求购'}}数量</view>
				<uni-easyinput color-gray v-model="num" :inputBorder="false" placeholder="请输入数量和单位，例如1吨  &nbsp;"></uni-easyinput>
			</view>
			<view pt14px pb14px border-b @click="showChooseAddress = true">
				<view flex items-center justify-between>
					<view>{{type? '供应' : '求购'}}地区</view>
					<view color-gray-5 text-xs>
						请选择地区 
						<text class="icon icon-angle-right mr-10px"></text>
					</view>		
				</view>
				<view flex flex-wrap>
					<view v-for="(value,index) in choosedAddress" :key="index" class="mt-10px mr-10px">
						<nut-tag type="primary" custom-color="#f1f1f1" text-color="#888" closeable @close="tagClose(index,value)">{{value.name}}</nut-tag>
					</view>
				</view>
			</view>
			<view flex items-center justify-between pt10px pb10px border-b v-if="!type">
				<view>{{type? '供应' : '求购'}}时效</view>
				<uni-data-picker :localdata="times" v-model="time" placeholder="请选择求购时效" popup-title="求购时效"></uni-data-picker>
			</view>
			<view pt14px pb14px border-b relative>
				<view pb10px>{{type? '供应' : '求购'}}描述</view>
				<textarea :maxlength="200" v-model="desc" p-10px bg-gray-1 w-full rounded placeholder="请详细描述您的求购信息，无需填写手机号，发布后将自动关联您的注册手机号~"/>
				<view absolute bottom-20px right-10px>{{ desc.length }} / 200</view>
			</view>
			<view pt14px pb14px>
				<view pb14px>产品图片</view>
				<uni-file-picker v-model="imageList" limit="3" @select="selectImage" @delete="deleteImage"  :auto-upload="false"></uni-file-picker>
			</view>

			<view fixed w-94vw bottom-20px left-3vw>
				<button w-full type="primary" rounded-100px :loading="loading" @click="submit">发布</button>
			</view>
		</view>
	
		<view flex fixed top-0 left-0 w-full h-100vh z-1000 bg-white v-show="showChooseAddress">
			<view w-2_sl_5 bg-gray-2 class="left-first">
				<view py-13px pl-20px :class="{'bg-color-white': index == currentFirstIndex}"
					v-for="(value,index) in addressFirst.addr" :key="value.id"
					@click="setCurrentFirstIndex(index)"
				>{{ value.name }}</view>
			</view>
			<view class="elevator-wrap" v-if="addressFirst.addr.length">
				<view v-for="(v,k) in addressFirst.addr[currentFirstIndex].children" :key="v.id" center justify-start pl-30px py-10px elevator-item @click="clickItem(k)">
					<view v-if="v.checked" class="icon icon-radio-checked text-base c-green-6"></view>
					<view v-else class="icon icon-radio text-base"></view>
					<view ml-15px>{{ v.name }}</view>
				</view>
			</view>
			<button absolute bottom-15px h-36px lh-36px right-1sl_20 w-1sl_2 type="primary" size="mini" rounded @click="showChooseAddress = false">确定</button>
		</view>

	</view>

</template>

<script setup>
	import api from '@/api'
	import { reactive, ref, computed } from 'vue'
	import { useBaseStore } from '@/stores/user'
	const {baseInfo} = useBaseStore()


	const { type } = defineProps({
		type: Number
	})
	uni.setNavigationBarTitle({
		title: type? '发布供应' : '发布求购'
	})

	const currentFirstIndex = ref(0)
	let addressFirst = reactive({		//加一层，防止接口赋值时丢失响应式
		addr: []
	})
	const setCurrentFirstIndex = index => {
		currentFirstIndex.value = index
	}
	const showChooseAddress = ref(false)
	const choosedAddress = ref([])

	const clickItem = k => {
		addressFirst.addr[currentFirstIndex.value].children[k].checked = !addressFirst.addr[currentFirstIndex.value].children[k].checked
		choosedAddress.value = addressFirst.addr.map(i => i.children).flat().filter(i => i.checked)
	}
	
	const tagClose = (index,value) => {
		choosedAddress.value = choosedAddress.value.filter((i,k) => k != index)
		const index1 = addressFirst.addr.findIndex(i => i.id == value.parent_id)
		const index2 = addressFirst.addr[index1].children.findIndex(i => i.id == value.id)
		addressFirst.addr[index1].children[index2].checked = !addressFirst.addr[index1].children[index2].checked
	}


	const types = ref([])		
	const typesPicked = ref('')
	const name = ref('')
	const price = ref('')
	const priceSwitch = ref(true)
	const switchChange = ({detail: {value}}) => {
		priceSwitch.value = value
	}

	const loading = ref(false)
	const num = ref('')
	const times = ref([])
	const time = ref('')
	const desc = ref('')
	const imageList = ref([])
	let realImages = []
	const selectImage = async ({tempFiles}) => {
		const file = tempFiles[0]
		const uploadRes = await api.uploadFile(file.url)
		if(uploadRes.images) {
			realImages.push(uploadRes.images)
		}
	}
	const deleteImage = ({index}) => {
		realImages.splice(index,1)
	}

	async function initData() {
		//获取地址
		let address = await api.getAddress({})
		if(address.length) {
			addressFirst.addr = address.map(i => {
				if(i.children && i.children.length) {
					for(let x = 0,len = i.children.length; x< len; x++) {
						i.children[x].checked = false
					}
				}else {
					i.children = [i]
					i.children[0].checked = false
				}
				return i
			})
		}
		//获取类型
		types.value = await api.goodsCatList({parent_id: 0})
		times.value = baseInfo.collective_consign_ageing.map(i => {
			return {
				text: i.name + '天',
				value: i.name
			}
		})
	}
	initData()

	const submit = async () => {
		if(!typesPicked.value) {
			uni.showToast({ title: '请选择类型', icon: 'none' })
			return
		}
		if(!name.value) {
			uni.showToast({ title: '请填写名称', icon: 'none' })
			return
		}
		if(!price.value && !priceSwitch.value) {
			uni.showToast({ title: '请填写价格', icon: 'none' })
			return
		}
		if(!num.value) {
			uni.showToast({ title: '请填写数量', icon: 'none' })
			return
		}
		if(!desc.value) {
			uni.showToast({ title: '请填写描述', icon: 'none' })
			return
		}

		const addressIds = choosedAddress.value.map(i => i.id)
		const submitRes = await api[type?'publishSupply':'publishRequire']({
			name: name.value,
			category: typesPicked.value,
			number: num.value,
			price: priceSwitch.value? '' : price.value,
			ageing: time.value,
			description: desc.value,
			images: JSON.stringify(realImages),
			region: JSON.stringify(addressIds),
		})
		if(submitRes.askbuy_id) {
			uni.showToast({ 
				title: '发布成功', 
				icon: 'none',
				success: () => {
					const timer = setTimeout(() => {
						uni.navigateBack()
						clearTimeout(timer)
					}, 2000);
				}
			})
		}
	}
	
</script>

<style lang="scss">
page {
  --nut-elevator-list-item-name-height: 40px;
	--nut-elevator-list-item-name-line-height: 40px;
	--nut-elevator-list-item-code-height: 50px;
	--nut-elevator-list-item-code-line-height:60px;
}
.bg-color-white {
	background-color: white;
}
.page-publish {
	
	.input-value {
		padding-left: 0;
	}
	.border-b{
		border-bottom: 1px solid #eee;
	}
	.uni-easyinput  {
		text-align: right;
	}
	.left-first {
		overflow: auto;
	}
	.input-value-border {
		border: none;
	}
	.elevator-wrap {
		flex: 1;
		position: relative;
    display: block;
    overflow: auto;
		padding-bottom: 120upx;
    box-sizing: border-box;

		.elevator-item {
			border-bottom: 1px solid #eee;
		}
	}

}



</style>
